<?php

class Login extends CI_Controller {
     function __construct() {
        parent::__construct();
        $this->load->model('manage_session');
        $this->load->model('manage_login');
        $this->load->library('tweet');
        $this->dataLogin = $this->manage_login->manageLogin();
        $fb_config = array(
            'appId'  => '264489850252668',
            'secret' => '150cc65835eb81c20faa114175539758',
            'cookie' => true,
        );
        $this->load->library('facebook', $fb_config);
    }

    function index() {

        $this->lang->load('main', 'english');
        $this->load->helper('form');
        $this->load->view('login_form',$this->dataLogin);
    }

    public function login_error($incorrect) {

        $this->dataLogin['incorrect'] = $incorrect;
        $this->lang->load('main', 'english');
        $this->load->helper('form');
        $this->load->view('login_form', $this->dataLogin);
    }

    function validate_credentials() {
        $this->load->model('membership_model');
        $query = $this->membership_model->validate();
        $user = $this->membership_model->getUserInfos($this->input->post('username'));
        if ($query) { 
            $this->manage_session->session($user[0]["user_id"],'LEAP');
            redirect('http://leapdemo.com');
        } else { // incorrect username or password
            $incorrect = "incorrect username or password";
            $this->login_error($incorrect);
        }
    }

    function signup() {

        $this->lang->load('main', 'english');
        $this->load->helper('form');
        $this->load->view('signup_form',$this->dataLogin);
    }
    function twitterSignup() {
        
        $this->lang->load('main', 'english');
        $this->load->helper('form');
        $tokens = $this->tweet->get_tokens();
        $user = $this->tweet->call('get', 'account/verify_credentials');
        $this->load->model('get_profile_infos');
        $this->manage_session->session($user->id_str,'TWITTER');
//        if($this->get_profile_infos->checkIfExists($user->screen_name)){
//            $this->load->view('close_popup'); 
//        }
        
            $this->load->view('twitter_signup_form',$user);
    }
    function create_member() {
        $this->load->library('form_validation');

        // field name, error message, validation rules
        $this->form_validation->set_rules('first_name', 'Name', 'trim|required');
        $this->form_validation->set_rules('last_name', 'Last Name', 'trim|required');
        $this->form_validation->set_rules('country', 'Country', 'trim|required');
        $this->form_validation->set_rules('email_address', 'Email Address', 'trim|required|valid_email');
        $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]|callback_username_check');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
        $this->form_validation->set_rules('password2', 'Password Confirmation', 'trim|required|matches[password]');


        if ($this->form_validation->run() == FALSE) {
            $this->load->view('signup_form',$this->dataLogin);
        } else {
            $this->load->model('membership_model');

            if ($this->membership_model->create_member()) {
                $this->lang->load('main', 'english');
                $this->load->view('login_form',$this->dataLogin);
            } else {
                $this->load->view('signup_form',$this->dataLogin);
            }
        }
    }
    function username_check($username)
	{
           $this->load->model('get_profile_infos');
		if ($this->get_profile_infos->checkIfExists($username))
		{
			$this->form_validation->set_message('username_check', 'The %s field can not be "'.$username.'"');
			return FALSE;
		}
                if(preg_match ('/[^a-z0-9]/i', $username)){
                        $this->form_validation->set_message('username_check', 'The %s field cannot contain spaces or special Characters !');
                        return FALSE;
                }
		else
		{
			return TRUE;
		}
    }
    function loginTwitter() {
        
        $this->tweet->set_callback(site_url('/login/twitterSignup'));
        $this->tweet->login();
    }
    function logoutTwitter() {
        $this->session->sess_destroy();
        $this->session->unset_userdata('LEAP_TWITTER_SESS');
        $this->session->unset_userdata('user_id');
        delete_cookie('LEAPSESSID');
        delete_cookie('LEAPSESSIF');
        $this->load->library('tweet');
        $this->tweet->logout();
        redirect('/');
    }
    function loginFacebook() {
        $config['enable_query_strings'] = TRUE;
//        $request_uri = $_SERVER['REQUEST_URI'];
//        $request_uri = explode('?', $request_uri);
//        if (count($request_uri) > 1) {
//            parse_str($request_uri[1], $_REQUEST);
//        }
        $user = $this->facebook->getUser();
        
        if($user){
            $data['user_profile'] = $this->facebook->api('/me');
            $this->manage_session->session($user,'FACEBOOK');
        }
        $this->load->view('close_popup');
    }
    function loginFacebookInside(){
        $config['enable_query_strings'] = TRUE;
        $user = $this->facebook->getUser();
        if(!$user){
            $loginOptions = array(
                'domain' => 'http://leapdemo.com/',
                'scope' => 'email,user_about_me,publish_actions',
                'display' => 'popup',
                'redirect_uri' => 'http://leapdemo.com/login/loginFacebookInside',
            );
            redirect($this->facebook->getLoginUrl($loginOptions));
        }else{
          $this->load->view('close_popup');  
        }        
    }
    function logout() {
        $this->session->sess_destroy();
        delete_cookie('LEAPSESSID');
        delete_cookie('LEAPSESSIF');
        redirect('/');
    }

    function logoutFacebook() {
        $this->session->sess_destroy();
        delete_cookie('LEAPSESSID');
        delete_cookie('LEAPSESSIF');
        redirect('/');
//        redirect($_GET['url'] . "&access_token=" . $_GET['access_token']);
    }

}